package com.common.util;

import java.util.HashMap;
import java.util.Map;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 
 * 汉语拼音帮助类
 * 
 * @author 孙树林
 * 
 */
public class PinYinUtils {
	
	/** 全拼 */
	public static final String FULL_SPELL = "FULL";
	/** 简拼 */
	public static final String JANE_SPELL = "JANE";

	/**
	 * 汉语转换全拼
	 * 
	 * @param chinesWords
	 * @return
	 */
	public static Map<String, String> getPinYin(String chinesWords) {
		// 拼音
		Map<String, String> pinyin = new HashMap<String, String>();
		// 全拼
		StringBuilder full = new StringBuilder();
		// 简拼
		StringBuilder jane = new StringBuilder();
		if (StringUtils.isNotEmpty(chinesWords)) {
			HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
			format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
			format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
			format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
			char[] chines = chinesWords.toCharArray();
			for (char chine : chines) {
				String[] c;
				try {
					c = PinyinHelper.toHanyuPinyinStringArray(chine, format);
					if (!ArraysUtils.empty(c)) {
						full.append(c[0]);
						// 简拼
						String s = c[0];
						if(StringUtils.isNotEmpty(s)){
							jane.append(s.charAt(0));
						}
					} else {
						full.append(Character.toUpperCase(chine));
					}
				} catch (BadHanyuPinyinOutputFormatCombination e) {
					e.printStackTrace();
				}
			}
		}
		pinyin.put(FULL_SPELL, full.toString());
		pinyin.put(JANE_SPELL, jane.toString());
		return pinyin;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String words = "我是中国人,和测试单天假人";
		System.out.println("返回的拼音是： " + getPinYin(words).get(FULL_SPELL));
		System.out.println("返回的拼音是： " + getPinYin(words).get(JANE_SPELL));
	}
}
